
from appium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time, random, re
from appium.webdriver.common.touch_action import TouchAction
from appium.webdriver.common.mobileby import MobileBy
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
import datetime

# Appium 基本参数
from MyAutomator import MyAutomation

PLATFORM = 'Android'
DEVICE_NAME = 'MI_4S'
DRIVER_SERVER = 'http://localhost:4723/wd/hub'
TIMEOUT = 800
NORESET = 'True'
FLICK_STRAT_X = 300
FLICK_START_Y = 300
FLICK_DISTANCE = 700





class XiangKan(MyAutomation):

    def __init__(self, APP_PACKAGE, APP_ACTIVITY):

        # 圆形浮标
        self.coin_float_ele = 'com.xiangkan.android:id/coin_img_big'
        # 继续阅读对话框按钮
        self.coin_read_ele = 'com.xiangkan.android:id/tv_go_read'


        # video
        self.tryplay_ele = '//*[@text="视频"]'
        self.tryplay_item_ele = 'com.xiangkan.android:id/video_item_poster'


        # minivideo
        self.trysmplay_ele = '//*[@text="小视频"]'
        self.trysmplay_item_ele = 'com.xiangkan.android:id/iv_mini_video_cover'


        # read
        self.sh_menu_ele = '//*[@text="推荐"]'
        self.list_item_ele = 'com.xiangkan.android:id/tvTitle'
        self.return_ele = 'com.xiangkan.android:id/action_bar_back'
        self.return_video_ele = 'com.xiangkan.android:id/img_back'
        super().__init__(APP_PACKAGE, APP_ACTIVITY)

    # read
    def read_article(self, interval):

        sh_menu = self.wait.until(EC.presence_of_element_located((By.XPATH, self.sh_menu_ele)))
        sh_menu.click()
        print('点击顶部菜单:推荐...')
        time.sleep(2)
        start = time.time()

        for i in range(random.randint(2, 3)):
            self.swipeUp()
            time.sleep(random.randint(1, 3))
            print('第一次进入滑动列表')

        while True:
            try:
                articles = self.wait.until(EC.presence_of_all_elements_located((By.ID, self.list_item_ele)))
                print('新闻数量', len(articles))
                for article in articles:
                    try:
                        article.click()
                        print('进入新闻')

                        try:
                            coin_float = self.wait.until(EC.presence_of_element_located((By.ID, self.coin_float_ele)))
                            if coin_float != 'null':
                                try:
                                    # 新闻
                                    return_btn = self.wait.until(EC.presence_of_element_located((By.ID, self.return_ele)))
                                    if return_btn != 'null':
                                        for i in range(random.randint(5, 7)):
                                            time.sleep(random.randint(4, 6))
                                            self.swipeUpScope(0.6, 0.25)
                                    else:
                                        time.sleep(2)
                                except:
                                    # 视频
                                    return_btn = self.wait.until(EC.presence_of_element_located((By.ID, self.return_video_ele)))
                                    if return_btn!='null':
                                        print('视频关闭按钮 <')
                                        time.sleep(random.randint(30, 60))
                            else:
                                print('此为广告，应直接退出')

                        except:
                            print('其他类型新闻')

                        self.check_for_read_dialog()
                        # 返回
                        self.driver.press_keycode(4)
                        print('退出详情，回到列表1')
                    except:
                        print('退出详情，回到列表2')
            except:
                # 返回
                self.driver.press_keycode(4)
                print('退出详情，回到列表3')

            print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
            if random.randint(1, 5) >= 2:
                for i in range(random.randint(2, 3)):
                    time.sleep(random.randint(1, 3))
                    print('列表滑动')
                    self.swipeUp()
            else:
                sh_menu = self.wait.until(EC.presence_of_element_located((By.XPATH, self.sh_menu_ele)))
                sh_menu.click()
                print('点击顶部菜单:推荐...')
                time.sleep(random.randint(1, 3))
            end = start + interval
            now = time.time()
            if now >= end:
                print('结束新闻循环')
                break
            else:
                print('未到结束时间')



    # 视频
    def video(self, interval):
        sh_menu = self.wait.until(EC.presence_of_element_located((By.XPATH, self.tryplay_ele)))
        sh_menu.click()
        print('点击顶部菜单:推荐...')
        start = time.time()
        while True:
            try:
                articles = self.wait.until(EC.presence_of_all_elements_located((By.ID, self.tryplay_item_ele)))
                print('新闻数量', len(articles))
                for article in articles:
                    try:
                        article.click()
                        print('进入新闻')

                        time.sleep(random.randint(15, 40))

                        self.check_for_read_dialog()
                        # 返回
                        self.driver.press_keycode(4)
                        print('退出新闻进入菜单')
                    except:
                        print('看视频报错')
            except:
                self.swipeUp()

            for i in range(random.randint(2, 4)):
                time.sleep(random.randint(1, 3))
                print('菜单滑动')
                self.swipeUp()

            end = start + interval
            now = time.time()
            if now >= end:
                print('结束新闻循环')
                break
            else:
                print('未到结束时间')


    # 小视频
    def smallvideo(self, interval):
        try:
            tryplay = self.wait.until(EC.presence_of_element_located((By.XPATH, self.trysmplay_ele)))
            tryplay.click()
            video = self.wait.until(EC.presence_of_element_located((By.ID, self.trysmplay_item_ele)))
            video.click()
            print('打开短视频')
            start = time.time()
            while True:
                time.sleep(random.randint(5, 8))
                self.check_for_read_dialog()
                # if random.randint(0, 8) > 6:
                #     zanx = self.size['width'] * random.uniform(0.55, 0.65)
                #     zany = self.size['height'] * random.uniform(0.55, 0.65)
                #     TouchAction(self.driver).tap(zanx, zany,2).release().perform()

                self.swipeUp()
                end = start + interval
                now = time.time()
                if now >= end:
                    print('结束小视频循环')
                    break
        except:
            print('打开短视频失败')





    def check_for_read_dialog(self):
        try:
            sh_menu = self.wait.until(EC.presence_of_element_located((By.XPATH, self.tryplay_ele)))
            if sh_menu=='null':
                return
            else:
                sh_menu.click()
                time.sleep(2)
        except:
            print("无阅读红包弹框")



    # 入口函数
    def main(self):
        print('打开 {} App ...'.format('阅读'))
        #func_list = ['smallvideo', 'read_article', 'video']  # 新闻阅读，小视频，视频三个方法随机
        func_list = ['smallvideo']
        for i in range(12):
            exp = 'self.{}({})'.format(random.choice(func_list), random.randint(1000, 1200))
            print(exp)
            eval(exp)
            # home键
            self.driver.press_keycode(3)
            print('App {} 今日任务完成！'.format('阅读'))



#xiangkan
qutoutiao_appPackage = 'com.xiangkan.android'
qutoutiao_appActivity = 'com.bikan.reading.activity.SplashActivity'


if __name__ == '__main__':
    qutoutiao = XiangKan(qutoutiao_appPackage, qutoutiao_appActivity)
    qutoutiao.main()